<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>聊天页面</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: Arial, sans-serif;
        }

        body {
            background-color: #e5ddd5;
            height: 100vh;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }

        .app-container {
            display: flex;
            width: 95%;
            max-width: 1200px;
            height: 90vh;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }

        .conversation-list {
            width: 30%;
            background-color: #fff;
            border-right: 1px solid #eee;
            padding: 20px;
            overflow-y: auto;
        }

        .conversation-list h3 {
            margin-bottom: 10px;
        }

        .conversation-list ul {
            list-style-type: none;
        }

        .conversation-list li {
            padding: 10px;
            cursor: pointer;
            border-bottom: 1px solid #eee;
        }

        .conversation-list li:hover {
            background-color: #f0f0f0;
        }

        /*.chat-container {*/
        /*    width: 95%;*/
        /*    max-width: 800px;*/
        /*    height: 90vh;*/
        /*    background-color: #fff;*/
        /*    box-shadow: 0 2px 5px rgba(0,0,0,0.1);*/
        /*    display: flex;*/
        /*    flex-direction: column;*/
        /*}*/
        .chat-container {
            flex: 1;
            display: flex;
            flex-direction: column;
        }

        .message-list {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
            background-color: #e5ddd5;
            /*background-image: url('https://cdn.jsdelivr.net/gh/marscode/chat-bg@main/wechat-bg.png');*/
            background-size: cover;
            /* 隐藏滚动条样式 - WebKit 浏览器 */
            scrollbar-width: none; /* Firefox */
        }

        /* 隐藏滚动条样式 - WebKit 浏览器 */
        .message-list::-webkit-scrollbar {
            display: none;
        }

        .message {
            display: flex;
            align-items: flex-start;
            margin-bottom: 15px;
        }

        .message.user {
            justify-content: flex-end; /* 让用户消息整体靠右 */
            flex-direction: row; /* 反转头像和消息内容顺序 */
            margin-left: auto; /* 这会将整个消息块推到最右边 */
        }

        .message.user .avatar {
            order: 1; /* 将头像移到右侧 */
            margin-left: 10px; /* 调整头像与消息的间距 */
            margin-right: 0;
        }

        .message.bot {
            justify-content: flex-start;
        }

        .avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            margin: 0 10px;
        }

        .message-content {
            padding: 10px 15px;
            border-radius: 10px;
            max-width: 70%;
            position: relative;
        }

        .message.user .message-content {
            order: 0;
            background-color: #dcf8c6;
        }

        .message.bot .message-content {
            background-color: #fff;
        }

        .message.user .message-content::after {
            content: "";
            position: absolute;
            top: 10px;
            right: -10px; /* 调整用户消息气泡箭头位置到右边 */
            border-width: 10px;
            border-style: solid;
            border-color: transparent transparent transparent #dcf8c6;
        }

        .message.bot .message-content::before {
            content: "";
            position: absolute;
            top: 10px;
            left: -10px;
            border-width: 10px;
            border-style: solid;
            border-color: transparent #fff transparent transparent;
        }

        .current-message {
            padding: 10px 20px;
            border-top: 1px solid #eee;
            background-color: #f0f0f0;
        }

        .input-container {
            display: flex;
            gap: 8px;
            padding: 10px 20px;
            background-color: #f0f0f0;
        }

        #chat-input {
            flex: 1;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 20px;
            font-size: 1.2em;
            outline: none;
        }

        .send-button {
            background-color: #09d261;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 20px;
            cursor: pointer;
            font-size: 1.2em;
            transition: background-color 0.3s;
        }

        .send-button:hover {
            background-color: #07c156;
        }

        .conversation-list h3 {
            margin-bottom: 10px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        #new-chat-button {
            padding: 5px 10px;
            background-color: #09d261;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 0.9em;
            transition: background-color 0.3s;
        }

        #new-chat-button:hover {
            background-color: #07c156;
        }
    </style>
</head>
<body>
<div class="app-container">
    <!-- 会话列表 -->
    <div class="conversation-list">
        <h3>会话列表
            <button id="new-chat-button">new chat</button>
        </h3>
        <ul id="conversation-list-items"></ul>
    </div>
    <!-- 聊天容器 -->
    <div class="chat-container">
        <div class="message-list" id="message-list">
            <!-- 待显示的消息条目 -->
        </div>
        <div class="input-container">
            <textarea id="chat-input" placeholder="我发送" style="flex: 1; padding: 10px; border: 1px solid #ccc; border-radius: 20px; font-size: 1.2em; outline: none; resize: none; overflow-y: auto;"></textarea>
            <button class="send-button" id="send-button">发送</button>
            <!-- 添加暂停按钮 -->
            <button class="pause-button" id="pause-button" style="background-color: #ff4444; display: none;">暂停回复
            </button>
        </div>
    </div>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
    let eventSource = null;
    let isThinking = false;
    let thinkContentDiv = null;
    let thinkToggleSpan = null;
    let botMessageContent = null;
    var userId = getCookie("userId");
    var sessionId = getCookie("sessionId");
    $('#send-button').click(function () {
        const message = $('#chat-input').val();
        if (sessionId === "" || sessionId === undefined || sessionId === null || sessionId.length<10) {
            sessionId = shuffleStringFisherYates(userId)
            setCookie("sessionId", sessionId, 1);
        }
        if (message.trim() === '') {
            alert("请输入文字信息！")
            return;
        }
        var param = "?message=" + message + "&userId=" + getCookie("userId") + "&sessionId=" + getCookie("sessionId");
        eventSource = new EventSource(`/ai/generateStream` + param);
        $('#pause-button').show();
        // 构建动态结果
        var chatMessages = $('#message-list');
        var newMessage = $('<div class="message user"></div>');
        newMessage.append(`<img class="avatar" src="../imgs/user.png" alt="用户头像">`);
        newMessage.append(`<div class="message-content"><span class="nickname">${message}</span></div>`);
        // 将消息添加到消息列表末尾
        chatMessages.append(newMessage);
        var botMessage = $('<div class="message bot"></div>');
        botMessage.append(`<img class="avatar" src="../imgs/robot.png" alt="助手头像">`);
        botMessageContent = $('<div class="message-content"></div>');
        botMessage.append(botMessageContent);
        chatMessages.append(botMessage);
        // 流式输出
        eventSource.onmessage = function (event) {
            let data = event.data;
            let index = 0;
            data = data.replace(/\n/g, '<br>');
            while (index < data.length) {
                if (isThinking) {
                    const endIndex = data.indexOf('</think>', index);
                    if (endIndex !== -1) {
                        // 找到 </think>，添加内容并折叠
                        thinkContentDiv.append(data.substring(index, endIndex));
                        thinkContentDiv.hide();
                        isThinking = false;
                        index = endIndex + 8;
                    } else {
                        // 未找到 </think>，继续追加内容
                        thinkContentDiv.append(data.substring(index));
                        index = data.length;
                    }
                } else {
                    const startIndex = data.indexOf('<think>', index);
                    if (startIndex !== -1) {
                        // 找到 <think>，创建折叠元素
                        if (startIndex > index) {
                            botMessageContent.append(data.substring(index, startIndex));
                        }
                        thinkToggleSpan = $('<span class="think-toggle" style="cursor: pointer; color: blue; text-decoration: underline;">[思考内容]</span>');
                        thinkContentDiv = $('<div class="think-content"></div>');
                        botMessageContent.append(thinkToggleSpan);
                        botMessageContent.append(thinkContentDiv);
                        isThinking = true;
                        index = startIndex + 7;
                    } else {
                        // 未找到 <think>，直接添加内容
                        botMessageContent.append(data.substring(index));
                        index = data.length;
                    }
                }
            }

            // 绑定点击事件
            $('.think-toggle').off('click').on('click', function () {
                $(this).next('.think-content').toggle();
            });
        };
        // 将机器人消息添加到消息列表末尾
        chatMessages.append(botMessage);
        $('#chat-input').val('');
        eventSource.onerror = function (err) {
            eventSource.close();
            $('#pause-button').hide();
        };
    });
    // 暂停按钮点击事件
    $('#pause-button').click(function () {
        if (eventSource) {
            eventSource.close();
            $(this).hide(); // 隐藏暂停按钮
        }
    });

    // 定义一个函数用于清除指定名称的 cookie
    function clearCookie(name) {
        document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
    }

    // 页面加载完成时清除 sessionId 的 cookie
    window.addEventListener('load', function () {
        clearCookie('sessionId');
    });

    // 请求会话列表数据
    function loadConversationList() {
        $.ajax({
            url: '/ai/chatHistoryList?userId=' + userId,
            method: 'GET',
            success: function (data) {
                const listContainer = $('#conversation-list-items');
                listContainer.empty();
                data.forEach(function (item) {
                    const listItem = $('<li></li>').text(item.userMessages[0].toString());
                    listItem.click(function () {
                        if (eventSource) {
                            eventSource.close();
                        }
                        // 例如，清空聊天输入框和消息列表
                        $('#chat-input').val('');
                        $('#message-list').empty();
                        // 处理会话点击事件，例如加载该会话的聊天记录
                        console.log('点击了会话: ', item.sessionId);
                        clearCookie('sessionId');
                        setCookie('sessionId', item.sessionId, 1);
                        var msgArr = item.userMessages;
                        for (i = 0; i < msgArr.length; i++) {
                            var mesStr = msgArr[i].toString();
                            mesStr = mesStr.replace(/\n/g, '<br>');
                            var chatMessages = $('#message-list');
                            if (i % 2 === 0) {
                                var newMessage = $('<div class="message user"></div>');
                                newMessage.append(`<img class="avatar" src="../imgs/user.png" alt="用户头像">`);
                                newMessage.append(`<div class="message-content"><span class="nickname"></span></div>`);
                                newMessage.append(mesStr)
                                // 将消息添加到消息列表末尾
                                chatMessages.append(newMessage);
                            } else {
                                var botMessage = $('<div class="message bot"></div>');
                                botMessage.append(`<img class="avatar" src="../imgs/robot.png" alt="助手头像">`);
                                botMessageContent = $('<div class="message-content"></div>');
                                botMessageContent.append(mesStr);
                                botMessage.append(botMessageContent);
                                chatMessages.append(botMessage);
                            }
                        }

                    });
                    listContainer.append(listItem);
                });
            },
            error: function (error) {
                console.error('获取会话列表失败: ', error);
            }
        });
    }

    function shuffleStringFisherYates(str) {
        let arr = str.split('');
        for (let i = arr.length - 1; i > 0; i--) {
            // 生成一个从0到i的随机索引
            let j = Math.floor(Math.random() * (i + 1));
            // 交换元素
            [arr[i], arr[j]] = [arr[j], arr[i]];
        }
        return arr.join('');
    }

    // 定义一个函数用于设置 cookie
    function setCookie(name, value, days) {
        let expires = "";
        if (days) {
            const date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = "; expires=" + date.toUTCString();
        }
        document.cookie = name + "=" + (value || "") + expires + "; path=/";
    }

    function getCookie(name) {
        let nameEQ = name + "=";
        let ca = document.cookie.split(';'); // 分割所有的cookie字符串
        for (let i = 0; i < ca.length; i++) {
            let c = ca[i];
            while (c.charAt(0) === ' ') c = c.substring(1, c.length); // 移除前导空格
            if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length); // 返回cookie的值
        }
        return null; // 没有找到对应的cookie
    }

    function newChat() {
        // 为 new chat 按钮添加点击事件
        $('#new-chat-button').click(function () {
            if (eventSource) {
                eventSource.close();
            }
            // 这里可以添加创建新会话的逻辑
            console.log('点击了 new chat 按钮，开始创建新会话');
            // 例如，清空聊天输入框和消息列表
            $('#chat-input').val('');
            $('#message-list').empty();
            clearCookie('sessionId');
            let fisherYates = shuffleStringFisherYates(userId);
            setCookie('sessionId', fisherYates, 1);
            loadConversationList();
        });
    }
    // 页面加载完成后加载会话列表
    $(document).ready(function () {
        loadConversationList();
        newChat();

    });
</script>
</body>
</html>
